<template>
	<div class="div1">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>咨询师管理</el-breadcrumb-item>
		</el-breadcrumb>
	</div>
	<div>
		<div class="div2">
			<span class="spanTop">咨询师名称</span>
			<el-input size="large" v-model="searchName" style="width: 200px" placeholder="请输入咨询师名称" />
			<span class="spanTop">咨询师等级</span>
			<el-select v-model="searchCounselorLevelName" placeholder="请选择咨询师等级" size="large" style="width: 240px">

				<!-- TODO -->
				<el-option v-for="(item,index) in AllCounselorLevel" :value="item.id" :label="item.gradeName" />
			</el-select>
			<span class="spanTop">地址</span>
			<el-input size="large" v-model="searchAddress" style="width: 200px" placeholder="请输入地址" />
			<span class="spanTop">手机号</span>
			<el-input size="large" v-model="searchPhone" style="width: 200px" placeholder="请输入手机号" />
		</div>
		<el-button @click="query" type="primary" size="large" class="bt1">搜索</el-button>
		<el-button type="primary" @click="createOrUpdate()" size="large" class="bt1">新增咨询师</el-button>
		<el-button type="danger" size="large" class="bt1" @click="removeAll">批量删除</el-button>
		<el-table :data="tableData" style="width: 100%;margin-top: 10px;" border
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="50" />
			<el-table-column fixed prop="id" label="ID" width="60" />
			<el-table-column prop="consultName" label="咨询师名称" min-width="120" />
			<el-table-column prop="consultGradeEntity.gradeName" label="咨询师等级" width="110" />
			<el-table-column prop="mobile" label="手机号" width="110" />
			<el-table-column prop="email" label="邮箱" min-width="160" show-overflow-tooltip />
			<el-table-column label="头像" width="100">
				<template #default="scope">
					<el-avatar shape="square" size="large" :src="imgUrl + scope.row.avatarUrl" />
				</template>
			</el-table-column>
			<el-table-column label="证书图片" width="100">
				<template #default="scope">
					<el-avatar shape="square" size="large" :src="imgUrl + scope.row.certImg" />
				</template>
			</el-table-column>

			<!-- <el-table-column prop="address" label="擅长领域" min-width="120" show-overflow-tooltip /> -->

			<el-table-column label="擅长领域" min-width="120">
				<template #default="scope">
					<!-- 把逗号替换成 <br> 标签 -->
					<span v-html="expertiseMap[scope.row.id]?.replace(/,/g, '<br>') || ''"></span>
				</template>
			</el-table-column>




			<el-table-column prop="address" label="所属地址" min-width="120" show-overflow-tooltip />
			<el-table-column prop="introduction" label="咨询师简介" min-width="200" show-overflow-tooltip />
			<el-table-column label="职位" width="100">
				<template #default="scope">
					<div class="jobOne" v-if="scope.row.job=='1'">咨询师</div>
					<div class="jobTwo" v-else>心理导师</div>
				</template>
			</el-table-column>
			<el-table-column fixed="right" label="操作" width="200">
				<template #default="scope">
					<el-button type="primary" @click="createOrUpdate(scope.row)">编辑</el-button>
					<el-button type="danger" @click="remove(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>



		<el-dialog v-model="dialogFormVisible" :title="form.id.length==0?'新增咨询师':'编辑咨询师'" width="800"
			style="margin-bottom: 60px;" @close="handleClose">
			<el-form>
				<el-form-item label="咨询师名称" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.consultName" autocomplete="off" placeholder="请输入咨询师名称" />
				</el-form-item>

				<el-form-item label="咨询师等级" :label-width="formLabelWidth" style="clear: left;">
					<el-select v-model="form.consultGrade" placeholder="请选择咨询师等级" size="large" style="width: 240px">
						<el-option v-for="(item,index) in AllCounselorLevel" :value="item.id" :label="item.gradeName" />
					</el-select>
				</el-form-item>
				<el-form-item label="手机号" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.mobile" autocomplete="off" placeholder="请输入手机号" />
				</el-form-item>
				<el-form-item label="邮箱" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.email" autocomplete="off" placeholder="请输入邮箱" />
				</el-form-item>
				<el-form-item label="头像图片">
<<<<<<< HEAD
					<el-upload action="http://121.43.133.75:8080/upload" list-type="picture-card"
=======
					<el-upload :action="baseURL+'upload'" list-type="picture-card"
>>>>>>> 4b91f5d65e9fe8ca84f03b15100e1d5717773ad9
						:on-success="(res, file) => handleSuccess(res, file, avatarFileList, 'avatar')" :limit="1"
						:on-preview="handlePictureCardPreview" :file-list="avatarFileList"
						:on-remove="(file, fileList) => handleRemove(file, fileList, 'avatar')">
						<el-icon style="width: 128px; height: 128px;border: 1px
dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
							<Plus />
						</el-icon>
					</el-upload>
					<!-- 放大预览组件: 和官网一致 -->
					<el-dialog v-model="dialogVisible">
						<img w-full :src="dialogImageUrl" alt="Preview Image" />
					</el-dialog>
				</el-form-item>
				<el-form-item label="证书图片">
<<<<<<< HEAD
					<el-upload action="http://121.43.133.75:8080/upload" list-type="picture-card"
=======
					<el-upload :action="baseURL+'upload'" list-type="picture-card"
>>>>>>> 4b91f5d65e9fe8ca84f03b15100e1d5717773ad9
						:on-success="(res, file) => handleSuccess(res, file, certFileList, 'cert')" :limit="1"
						:on-preview="handlePictureCardPreview" :file-list="certFileList"
						:on-remove="(file, fileList) => handleRemove(file, fileList, 'cert')">
						<el-icon
							style="width: 128px; height: 128px;border: 1pxdashed #DCDFE6; border-radius: 5px;font-size: 20px;">
							<Plus />
						</el-icon>
					</el-upload>
					<!-- 放大预览组件: 和官网一致 -->
					<el-dialog v-model="dialogVisible">
						<img w-full :src="dialogImageUrl" alt="Preview Image" />
					</el-dialog>
				</el-form-item>
				<el-form-item label="所属地址" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.address" autocomplete="off" placeholder="请上传所属地址" />
				</el-form-item>
				<el-form-item label="咨询师简介" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.introduction" autocomplete="off" placeholder="请上传咨询师简介" />
				</el-form-item>
				<el-form-item label="咨询师分类" :label-width="formLabelWidth" style="clear: left;">
					<el-select v-model="form.job" placeholder="请选择咨询师分类" size="large" style="width: 240px">
						<el-option :value="1" label="咨询师" />
						<el-option :value="2" label="心理导师" />
					</el-select>
				</el-form-item>

				<el-form-item label="擅长领域" :label-width="formLabelWidth" style="clear: left;">
					<!-- selectedExpertIds   已选 id 数组 -->
					<el-select v-model="selectedExpertIds" placeholder="请选择擅长领域" multiple collapse-tags
						collapse-tags-tooltip :max-collapse-tags="3" :multiple-limit="3" style="width: 240px">
						<el-option v-for="item in expertList" :key="item.id" :label="item.expertise" :value="item.id" />
					</el-select>
				</el-form-item>


			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取消</el-button>
					<el-button @click="dialogFormVisible = false,add()">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>
		<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10,15, 20]"
			:size="size" layout="total, sizes, prev, pager, next, jumper" :total=" total"
			@size-change="handleSizeChange" @current-change="handleCurrentChange" v-if="total !=0" />
	</div>
</template>
<script setup>
	import {
		onMounted,
		ref,
		reactive,
		computed,
		watch
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	import {
		getCurrentInstance
	} from 'vue';
	import {
		cloneDeep
	} from 'lodash-es'; // 推荐 lodash-es
	import http from '@/util/http';

	const axios = getCurrentInstance().appContext.config.globalProperties.axios
	const tableData = ref([])
	const currentPage = ref(1) // 当前页
	const pageSize = ref(5) // 每页显示条目数
	const size = 'default' // 分页大小
	const total = ref(0)
	const searchName = ref('')
	const searchCounselorLevelName = ref('')
	const searchAddress = ref('')
	const searchPhone = ref('')
	// const imgUrl = "http://localhost:8080"
<<<<<<< HEAD
const imgUrl = ""
=======
	const imgUrl = ''
>>>>>>> 4b91f5d65e9fe8ca84f03b15100e1d5717773ad9

	const form = ref({
		address: "",
		avatarUrl: "",
		email: "",
		certImg: "",
		consultGradeEntity: {
			// id:"",
			gradeName: ""
		},
		consultName: "",
		mobile: "",
		job: "",
		introduction: "",
		id: "",
	})
	const baseURL = http.defaults.baseURL

	const dialogFormVisible = ref(false)
	const formLabelWidth = '100px'
	const AllCounselorLevel = ref([]) // 获取咨询师等级信息



	// 查询擅长领域列表
	const expertList = ref({})
	const selectedExpertIds = ref([]); // 已选 id 数组


	// 查询咨询师的擅长领域
	const expertiseMap = ref({})
	const expertQuery = () => {
		axios.get('consultExpertise/selectConsultExpert').then(res => {
			console.log(res);
			res.data.forEach(item => {
				expertiseMap.value[item.id] = item.expertise;
			});
		});
	};

	function query() {
		axios.get(
			`consult/page?consultName=${searchName.value}&consultGrade=${searchCounselorLevelName.value}&address=${searchAddress.value}&mobile=${searchPhone.value}&pageNum=${currentPage.value}&pageSize=${pageSize.value}`,
		).then(resp => {
			tableData.value = resp.data.list;
			for (let i = 0; i < resp.data.list.length; i++) {
				if (resp.data.list[i].job == '咨询师') {
					tableData.value[i].job = 1
				} else {
					tableData.value[i].job = 2
				}
			}
			// if(resp.data.list.job == '咨询师'){
			// 	tableData.value.job=1
			// }else{
			// 	tableData.value.job=2
			// }
			total.value = resp.data.total
			console.log(resp);
		})
		axios.get('expertiseAreas').then(resp => {
			expertList.value = resp.data
			console.log("expert=", expertList.value);
		})
	}
	const findClassify = () => {
		axios.get('consultGrade').then((resp) => {
			AllCounselorLevel.value = resp.data
		})
	}


	const handleSizeChange = (val) => {
		pageSize.value = val;
		query();
		expertQuery();
	}
	const handleCurrentChange = (val) => {
		currentPage.value = val
		query();
		expertQuery();
	}
	const handleClose = () => {
		form.value = {
			address: "",
			avatarUrl: "",
			email: "",
			certImg: "",
			consultGrade: '',
			consultName: "",
			mobile: "",
			job: '',
			introduction: "",
			id: '',
		}
		console.log(selectedExpertIds.value);
		selectedExpertIds.value = []
	}


	// 图片上传
	const dialogImageUrl = ref('') // 图片预览框的地址
	const dialogVisible = ref(false) // 控制图片预览框是否显示
	const fileList = ref([])
	// 上传成功的回调
	const handleSuccess = (res, file, fileList, type) => {
		console.log("图片上传成功", res)
		const imgPath = res.data // 假设 res.data 是上传后的路径

		if (type === 'avatar') {
			form.value.avatarUrl = imgPath
			avatarFileList.value = [{
				name: imgPath.split('/').pop(),
				url: imgUrl + imgPath
			}]
		} else if (type === 'cert') {
			form.value.certImg = imgPath
			certFileList.value = [{
				name: imgPath.split('/').pop(),
				url: imgUrl + imgPath
			}]
		}
	}
	// 删除图片
	const handleRemove = (file, fileList, type) => {
		if (type === 'avatar') {
			form.value.avatarUrl = ''
			avatarFileList.value = []
		} else if (type === 'cert') {
			form.value.certImg = ''
			certFileList.value = []
		}
	}
	// 处理图片预览
	const handlePictureCardPreview = (file) => {
		dialogImageUrl.value = file.url;
		dialogVisible.value = true;
	}

	const avatarFileList = ref([]) // 头像
	const certFileList = ref([]) // 证书


	let cId = 0;

	const createOrUpdate = (row) => {
		dialogFormVisible.value = true

		// 先清空
		avatarFileList.value = []
		certFileList.value = []

		if (row != null && row != '') {
			axios.get(`consult/${row.id}`).then((resp) => {
				console.log('点击编辑得到的：', resp);
				form.value = resp.data

				/* ---------- 头像回显 ---------- */
				if (resp.data.avatarUrl) {
					avatarFileList.value = [{
						name: resp.data.avatarUrl.split('/').pop(),
						url: imgUrl + resp.data.avatarUrl
					}]
				}

				/* ---------- 证书回显 ---------- */
				if (resp.data.certImg) {
					certFileList.value = [{
						name: resp.data.certImg.split('/').pop(),
						url: imgUrl + resp.data.certImg
					}]
				}

			})
			axios.get(`consultExpertise/selectConsultExpert/${row.id}`).then((resp) => {
				console.log("咨询师的擅长领域id", resp.data);
				selectedExpertIds.value = JSON.parse(resp.data.exceptList || '[]');

			})
		} else {
			console.log('点击新增');
		}
	}
	const add = () => {
		console.log("新增的id", form.value.id);
		console.log(form.value.job);
		if (form.value.job == 1||form.value.job == '咨询师') {
			form.value.job = '咨询师'
		} else {
			form.value.job = '心理导师'
		}

		if (form.value.id.length === 0) {
			axios.post(`/consult?list=${selectedExpertIds.value}`, {
				address: form.value.address,
				avatarUrl: form.value.avatarUrl,
				email: form.value.email,
				certImg: form.value.certImg,
				consultGrade: form.value.consultGrade,
				consultName: form.value.consultName,
				mobile: form.value.mobile,
				job: form.value.job,
				introduction: form.value.introduction,
				id: '',
				list: selectedExpertIds.value
			}).then((resp) => {
				console.log("添加返回结果", resp);
				if (resp.code == 200) {
					ElMessage.success("新增成功")
				} else {
					ElMessage.error(resp.data)
				}
			})
		} else {
			console.log(avatarFileList.value);
			console.log("修改工作是",form.value.job);

			axios.put('consult', {
				address: form.value.address,
				avatarUrl: form.value.avatarUrl,
				email: form.value.email,
				certImg: form.value.certImg,
				consultGrade: form.value.consultGrade,
				consultName: form.value.consultName,
				mobile: form.value.mobile,
				job: form.value.job,
				introduction: form.value.introduction,
				id: form.value.id,
				list: selectedExpertIds.value
			}).then((resp) => {
				console.log('触发修改请求', resp);
				if (resp.code == 200) {
					ElMessage({
						message: '修改成功',
						type: 'success',
					})
				} else {
					ElMessage.error('修改失败')
				}
			}).finally(() => {
				query();
				expertQuery();
			});
		}
	}

	const remove = (row) => {
		console.log('当前行的数据', row);
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'删除', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete(`consult/${row.id}`).then((resp) => {
					console.log('删除后：', resp);
					if (resp.code == 200) {
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					} else {
						ElMessage.error('删除失败')
					}
				}).finally(() => {
					query();
					expertQuery();
				});

			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})

	}
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.id
		})
		console.log(multipleSelection.value);
	}
	const removeAll = (row) => {
		console.log('当前行的数据', row);
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'删除', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete(`consult`, {
					params: {
						ids: multipleSelection.value.join(',')
					}
				}).then(resp => {
					if (resp.code == 200) {
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					} else {
						ElMessage.error('删除失败')
					}
				}).finally(() => {
					query();
					expertQuery();
				});
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}
	onMounted(() => {
		query();
		findClassify();
		expertQuery();
	})
</script>
<style scoped>
	.jobOne {
		width: 78px;
		background-color: #ecf5ff;
		border: 1px solid #d9ecff;
		color: #44a0ff;
		text-align: center;
		border-radius: 5px;
		padding: 5px 10px;
	}

	.jobTwo {
		width: 78px;
		background-color: #fef0f0;
		border: 1px solid #fde2e2;
		color: #f56d6d;
		text-align: center;
		border-radius: 5px;
		padding: 5px 10px;
	}

	.spanTop {
		margin: 0 10px;
		color: #696a6e;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.bt1 {
		margin-top: 10px;
		margin-left: 10px;
	}

	.div1 {
		border-bottom: 1px solid #eeeeee;
		width: 100%;
		height: 30px;
		padding-top: 15px;
		padding-left: 15px;
	}

	.div2 {
		padding-top: 15px;
	}

	.el-table {
		margin-left: 10px;
	}

	.el-pagination {
		margin-top: 10px;
		margin-left: 10px;
	}
</style>